import { Injectable } from '@nestjs/common';
import { CreateMangerDto } from './dto/create-manger.dto';
import { UpdateMangerDto } from './dto/update-manger.dto';
import { Manger } from './entities/manger.entity';
import type { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';

@Injectable()
export class MangerService {
  constructor(
    @InjectRepository(Manger) private readonly manger: Repository<Manger>,
  ) {}
  create(createMangerDto: CreateMangerDto) {
    const manger = new Manger();
    manger.name = createMangerDto.name;
    manger.money = createMangerDto.money;
    this.manger.save(manger);
    return 'success';
  }

  findAll() {
    return `This action returns all manger`;
  }

  findOne(id: number) {
    return `This action returns a #${id} manger`;
  }

  update(id: number, updateMangerDto: UpdateMangerDto) {
    return `This action updates a #${id} manger`;
  }

  remove(id: number) {
    return `This action removes a #${id} manger`;
  }
  transFerMoney(transFerMoneyDto) {
    try {
      return this.manger.manager.transaction(async (manger) => {
        const from = await this.manger.findOne({
          where: { id: transFerMoneyDto.fromId },
        });
        const to = await this.manger.findOne({
          where: { id: transFerMoneyDto.toId },
        });
        if (from.money >= transFerMoneyDto.money) {
          manger.save(Manger, {
            id: from.id,
            money: from.money - transFerMoneyDto.money,
          });
          manger.save(Manger, {
            id: to.id,
            money: to.money + transFerMoneyDto.money,
          });
          return '转账成功';
        } else {
          return {
            data: '余额不足',
            msg: '转账失败',
          };
        }
      });
    } catch (e) {
      throw new Error(e);
    }
  }
}
